package com.qf.Fileter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

@WebFilter("/*")
public class CharacterFilter implements Filter {
    public void destroy() {
        System.out.println("全局过滤器被销毁了");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //获取请求对象HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) req;
        //获取相应对象HttpServletResponse
        HttpServletResponse response = (HttpServletResponse) resp;
        //获取前台的提交方式
        String method = request.getMethod();
        //判断如果是post提交
        if ("POST".equals(method)){
            request.setCharacterEncoding("utf-8");

        }
        //如果又响应,解决响应乱码
        response.setContentType("text/html;charset=utf-8");
        //释放请求
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {
        System.out.println("全局过滤器开始初始化了");
    }

}
